package cn.javaxc.model.page;

import java.io.*;
import java.net.SocketException;
import java.sql.*;
import java.util.*;
import javax.servlet.http.HttpServletRequest;

import cn.javaxc.mvcwork.util.io.CommonPartRequest;
import cn.javaxc.mvcwork.controller.*;
import cn.javaxc.mvcwork.controller.web.*;
import cn.javaxc.mvcwork.framework.actions.TActionContext;
import cn.javaxc.model.page.*;
import cn.javaxc.mvcwork.modules.file.*;
import cn.javaxc.mvcwork.util.helper.*;
import cn.javaxc.mvcwork.util.common.*;
import cn.javaxc.mvcwork.action.MVCAction;

import cn.javaxc.mvcwork.controller.AppUtils;
import cn.javaxc.mvcwork.framework.actions.*;
import cn.javaxc.mvcwork.modules.login.UserBean;
import cn.javaxc.mvcwork.util.io.ImageUtils;
public class VUEPageFile 
{ 
	/**
	 * 数据库连接
	 */
//	public Connection db=null;
	/**
	 * 包含上下文处理中的Request与Response对象
	 */
	public TActionContext context=null;
	public VUEPage page=null;
	private boolean error=false;
	public void setPage(VUEPage page){
		this.page=page;
//		this.db=page.db;
		this.context=page.context;
	}
	public boolean hasError(){
		return this.error;
	}
	private void setError(boolean error){
		this.error=error;
	}
//	protected HttpMultiPartParser doParseFile(String filePath) throws Exception{
//		  //Process the form data
//		  HttpMultiPartParser multiPart = new HttpMultiPartImpl();
//		  multiPart.setUsePathParam(false);
//		  multiPart.setUseUniqueName(true);
//		  multiPart.setUseDateForFolder(true);
//		  multiPart.setExtensionId(AppUtils.getUserId(context));
//		  multiPart.parseData(context.getRequest(), filePath);
//		  return multiPart;
//	}
	protected void doInsertFileContent(FileItem thisItem)throws SQLException{

	}
 public String doInsertFile(boolean b_insert) throws Exception{
		if(!page.hasUserPermission())return page.PermissionError;
    AppUtils.addFormElements(context);

    boolean isValid = false;
    boolean recordInserted = false;
	String type=null;
	String result="Submit";


	  Object moduleId = RequestHelper.getRequestValue(context.getRequest(),"CMODULEID");
	  if (StringUtils.isNullData(moduleId)){
		moduleId="upload";
	  }
	  


	  String modulePath=AppUtils.getModuleFileLibrary(moduleId);
	  if (modulePath==null){
		setError(true);
		context.setActionError( "MODULEID ERROR");
        return (page.SystemError); 
	  }
      String filePath = AppUtils.getModuleFileLibrary(context, modulePath);
//  	  HttpMultiPartParser httppart =doParseFile(filePath);
	  if (context.getRequest() instanceof CommonPartRequest){
//		
	  CommonPartRequest httppart=(CommonPartRequest)context.getRequest();
	  httppart.parseData(filePath);
	  Map<String, List> parts = (Map)httppart.getMultiPart().getMultipartFiles();
	  VUEFormBean emtMap=(VUEFormBean)context.getFormBean();
	  /////////////////////////////////////////
	  Object itemId = RequestHelper.getRequestValue(httppart,"link_item_id");
	  int fileId = CommonUtil.parseInt(RequestHelper.getRequestValue(httppart,"fileid"),-1);
	  int folderId = CommonUtil.parseInt(RequestHelper.getRequestValue(httppart,"folder_id"),-1);
	  double version = CommonUtil.parseDouble(RequestHelper.getRequestValue(httppart,"version"),1.0);

	  FrameLog.info(this.getClass().getName()+" fileId:"+fileId+" version:"+version);
	  Map<String, String[]> files=httppart.getMultipartParameters();
	 if (b_insert){
		
		  
	  for (String v_name: parts.keySet()){ 
		  List<String> fileids=new ArrayList();
		  for (Object obj:parts.get(v_name)){		  
			
			//Update the database with the resulting file
			FileInfo newFileInfo = (FileInfo)obj;
//			emtMap.getParameterFile().put(v_name,newFileInfo);

			FileItem thisItem = new FileItem();
			thisItem.setLinkModuleId(moduleId);
			thisItem.setLinkItemId(itemId);
			thisItem.setEnteredBy(CommonUtil.parseInt(MSecurityUtils.getUserId()));
			thisItem.setModifiedBy(CommonUtil.parseInt(MSecurityUtils.getUserId()));
			thisItem.setFolderId(folderId);
			if (StringUtils.isNullData(httppart.getParameter("subject"))){
				thisItem.setSubject(StringUtils.getPrefix(newFileInfo.getOriginalFilename(),"."));
			}else{
				thisItem.setSubject(httppart.getParameter("subject"));
			}
			thisItem.setClientFilename(newFileInfo.getOriginalFilename());
			thisItem.setFilename(newFileInfo.getRealFilename());
			thisItem.setVersion(version);
			thisItem.setSize((int)newFileInfo.getSize());
			if (!thisItem.hasErrors()) {
				if (fileId>0&&version>0){
					FileItem _fitem=new FileItem(fileId);

					_fitem.buildVersionList();
					if(thisItem.getVersion(version)!=null){
						setError(true);
						context.setActionError( "已经存在此版本");
						return (page.SystemError); 
					}else{
						thisItem.setId(fileId);
						thisItem.setVersion(version);
						recordInserted = thisItem.insertVersion();
					}
				}else{
					recordInserted = thisItem.insert();
				}
			}else{
				setError(true);
//				AppUtils.setSourcePage(context);
				return page.ONSUBMIT;
			}
			thisItem.setDirectory(filePath);
			if (Boolean.valueOf(context.getConfig().getClassProperty(MVCAction.class,"InsertThumbFile","false"))){
				if (thisItem.isImageFormat()) {
				  //Create a thumbnail if this is an image
				  File thumbnailFile = new File(
					  newFileInfo.getLocalFile().getPath() + "TH");
				  cn.javaxc.mvcwork.util.io.ImageUtils.saveThumbnail(newFileInfo.getLocalFile(), thumbnailFile, 133d, 133d);
				  //Store thumbnail in database
				  Thumbnail thumbnail = new Thumbnail();
				  thumbnail.setId(thisItem.getId());
				  thumbnail.setFilename(newFileInfo.getRealFilename() + "TH");
				  thumbnail.setVersion(thisItem.getVersion());
				  thumbnail.setSize((int) thumbnailFile.length());
				  thumbnail.setEnteredBy(thisItem.getEnteredBy());
				  thumbnail.setModifiedBy(thisItem.getModifiedBy());
				  thumbnail.insert();
				}
			}
			doInsertFileContent(thisItem);
			fileids.add(thisItem.getId()+"");

			

			

			
		  } 
			if (v_name.endsWith("MVC_FILE")){
				files.put(v_name.replace("MVC_FILE","fileid"), fileids.toArray(new String[0]));
			}else{
				files.put(v_name, fileids.toArray(new String[0]));
			}
		  }
		  
	  }else{
			for (String v_name: parts.keySet()){
		  
		  
			  if (parts.get(v_name) instanceof FileInfo) {
				FileInfo info=(FileInfo)(FileInfo)parts.get(v_name);
//				emtMap.getParameterFile().put(v_name,parts.get(v_name));
				files.put(v_name, new String[]{"/"+moduleId+"/"+info.getSaveFileName()});
				files.put(v_name+"_default", new String[]{"/"+moduleId+"/"+info.getSaveFileName()});
			  } 
		  }
	  }
	  
//	  parts.putAll(files);
//		context.setRequest(httppart.getRequest(context.getRequest()));
		
		
//		emtMap.setParameter(parts);
		populateBean(emtMap);
	}
    return page.ONSUBMIT;
	
  }	
	protected void populateBean(Object bean) {

	}
}
